<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\ocean;

use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\model\ClientAccountModel;
use app\model\mongo\MongoOeVideoModel;
use app\model\OeSchemaUrlModel;
use app\model\OeSchemaVideoModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class SchemaVideoEfficiencyService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_LOCK_KEY]['schema_video_efficiency'];

    /**
     * 拉取数据.
     * @param string $advertiserId 广告主id
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getVideoList(string $advertiserId = ''): bool
    {
        // 获取账户信息
        $obj = AccountService::getAccountModel(0, $advertiserId);
        if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
            return self::setError('账户数据不存在');
        }
        try {
            $videos = (new MongoOeVideoModel())->where('account_id', $obj->getKey())->where('is_good', 0)->select();
            foreach ($videos as $video) {
                $isExist = (new OeSchemaVideoModel())->where('account_id', $obj->getKey())->where('video_id', $video['video_id'])->find();
                if ($isExist instanceof OeSchemaVideoModel && $isExist->getKey()) {
                    $count = (new OeSchemaVideoModel())->where('schema_url_id', $isExist->getAttr('schema_url_id'))->count();
                    (new OeSchemaUrlModel())->where('id', $isExist->getAttr('schema_url_id'))->update(['video_num' => $count]);
                    $isExist->delete();
                }
            }
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

}
